package com.ybkj.daijia.api.member.v3;

import com.ybkj.daijia.api.member.ErrorConstant;
import com.ybkj.daijia.api.member.SecurityUtils;
import com.ybkj.daijia.api.member.transport.ResultTransport;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.MemberNotice;
import com.ybkj.daijia.server.model.NoticeXPassenger;
import com.ybkj.daijia.server.service.MemberNoticeService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.NoticeXPassengerService;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller("memberNoticeV3Controller")
@RequestMapping(value = "member/api/rest/v3")
public class NoticeController {

    private static final Logger logger = LoggerFactory.getLogger(NoticeController.class);

    @Autowired
    private MemberNoticeService memberNoticeService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private NoticeXPassengerService noticeXPassengerService;


    /**
     * 查询通知信息
     *
     * @param memberId
     * @param page
     * @param limit
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping("pageNotice")
    public @ResponseBody
    ResultTransport pageNotice(Long memberId, Integer page, Integer limit, String appKey,
        String token, String timestamp) {

        logger.debug("recv memberId:{},page:{},limit:{},appKey:{},token:{},timestamp:{}", memberId,
            page, limit, appKey, token, timestamp);

        if (null == memberId || null == page || null == limit || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

//		if (!StringUtils.isNumeric(timestamp)
//				|| !SecurityUtils.checkTimestamp(Long.parseLong(timestamp))) {
//			return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
//		}

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(memberId));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Passenger passenger = memberService.findOnePassenger(memberId);
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        try {

            Page<Map<String, Object>> notice = memberNoticeService
                .pageNotice(passenger, page, limit);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(notice);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v3 member pageNotice error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 微信公众号V5分页获取通知
     *
     * @param memberId 客户ID
     * @param page     页码
     * @param limit    条数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "pageNoticeV5", method = {RequestMethod.GET})
    public ResultTransport pageNoticeV5(Long memberId, Integer page, Integer limit) {

        if (null == memberId || null == page || null == limit) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        Passenger passenger = memberService.findOnePassenger(memberId);
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }

        try {

            Page<Map<String, Object>> notice = memberNoticeService
                .pageNotice(passenger, page, limit);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(notice);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v3 member pageNotice error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    @RequestMapping(value = "readNotice", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport readNotice(Long passengerId, Long noticeId, String appKey, String token,
        String timestamp) {

        logger.debug("recv passengerId:{},noticeId:{},appKey:{},token:{},timestamp:{}", passengerId,
            noticeId, appKey, token, timestamp);

        if (null == passengerId || null == noticeId || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(passengerId));
        params.add(String.valueOf(noticeId));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {
            NoticeXPassenger noticeXPassenger = noticeXPassengerService
                .findByPassengerAndNotice(passengerId, noticeId);

            if (null != noticeXPassenger) {
                noticeXPassengerService.updateHasRead(noticeXPassenger.getId());
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v3 member readNotice error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 微信公众号V5获取用户未读通知
     *
     * @param passengerId 客户ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getNotReadNoticesV5", method = RequestMethod.GET)
    public ResultTransport getNotReadNoticesV5(
        @RequestParam(required = true, value = "passengerId") Long passengerId) {
        ResultTransport result = null;
        try {
            List<Long> ids = noticeXPassengerService.selectNotReadNoticeIds(passengerId);
            result = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            result.setData(ids);
        } catch (Exception e) {
            e.printStackTrace();
            result = ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
        return result;
    }

    /**
     * 微信公众号V5更新通知已读
     *
     * @param passengerId 客户ID
     * @param noticeId    通知ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "readNoticeV5", method = RequestMethod.POST)
    public ResultTransport readNoticeV5(Long passengerId, Long noticeId) {

        if (null == passengerId || null == noticeId) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        try {

            NoticeXPassenger noticeXPassenger = noticeXPassengerService
                .findByPassengerAndNotice(passengerId, noticeId);
            if (null != noticeXPassenger) {
                noticeXPassengerService.updateHasRead(noticeXPassenger.getId());
            }
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v3 member readNotice error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 微信公众号获取通知详情
     *
     * @param id 通知ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "noticeInfoV5", method = {RequestMethod.GET})
    public ResultTransport noticeInfoV5(Long passengerId, Long id) {
        if (null == id) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }
        Passenger passenger = memberService.findOnePassenger(passengerId);
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS_ERROR);
        }
        MemberNotice notice = memberNoticeService.findOne(id);
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
        instance.setData(notice);
        return instance;
    }

    /**
     * 查询通知信息
     */
    @RequestMapping("viewNotice/{id}")
    public ModelAndView edit(@PathVariable("id") Long id) {

        ModelAndView mv = new ModelAndView();

        MemberNotice notice = memberNoticeService.findOne(id);

        mv.addObject("notice", notice);

        mv.setViewName("membernotice/view");

        return mv;
    }
}
